stripping whitespace in python

40

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'
'     hello world!    '.strip()
'hello world!'


'     hello world!    '.lstrip()
'hello world!    '

'     hello world!    '.rstrip()
'    hello world!'
greet = '      Hello Bob      '
# This is how we strip the whitespace at the beginning
print(greet.lstrip())       # Output: Hello Bob
                            # The whitespace at the end remains
# This is how we strip the whitespace at the end
print(greet.rstrip())       # Output:       Hello Bob
                            # The whitespace at the beginning remains
# This is how we strip the whitespaces at both the beginning and at the end
print(greet.strip())        # Output: Hello Bob
                            # White spaces at beginning and at end have removed
# But remember the initial string is not changed
print(greet)                # Output:       Hello Bob

Comments

Submit
0 Comments